﻿using Novacode;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using KingRoad.EPM.PersonnelLogEntity.Model;
using KingRoad.EPM.Web.Areas.PersonnelLog.ViewModels;
using KingRoad.EPM.Web.Areas.PersonnelLog.PersonnelLogFramework.Common;
using Unis.Framework.Core.Utility;
using System.Text;
using System.IO;

namespace KingRoad.EPM.Web.Areas.PersonnelLog.Controllers
{
    public class PlmSupervisorLogController : BaseController
    {
        /// <summary>
        /// 监理员日志列表
        /// </summary>
        /// <returns></returns>
        public ActionResult SupervisorLogList(string pageName)
        {
            var vm = new PlmSupervisorLogViewModel();
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = 1;
            //每页多少条
            ViewBag.numPerPage = 20;
            var list = PlmSupervisorlogUIRule.GetAllSupervisorlogForPage(ViewBag.pageNum, ViewBag.numPerPage, "Sl_timestamp", out totalRecord, " Sl_ContractNumber in (" + Get_JL_JC_ZDJL_SG_SegmentCodes() + ") ");
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;

            vm.ThePlmSupervisorlogList = list;
            //  return View(vm);
            return String.IsNullOrEmpty(pageName) ? View(vm) : View(pageName, vm);
        }

        /// <summary>
        /// 费用计划-列表(分页提交)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SplitPage()
        {
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);
            if (ViewBag.pageNum == 0 || ViewBag.numPerPage == 0)
                return SupervisorLogList("SupervisorLogList");

            ViewBag.Sl_SupervisorName = Request.Form["Sl_SupervisorName"];
            ViewBag.Sl_SupervisionNumber = Request.Form["Sl_SupervisionNumber"];
            ViewBag.Sl_RecordDate = Request.Form["Sl_RecordDate"];
            ViewBag.Sl_ContractNumber = Request.Form["Sl_ContractNumber"];
            string sql = " Sl_ContractNumber in (" + Get_JL_JC_ZDJL_SG_SegmentCodes() + ") ";
            if (ViewBag.Sl_SupervisorName != "")
                sql += " and Sl_SupervisorName like '%" + ViewBag.Sl_SupervisorName + "%' ";
            if (ViewBag.Sl_SupervisionNumber != "")
                sql += " and Sl_SupervisionNumber like '%" + ViewBag.Sl_SupervisionNumber + "%' ";
            if (ViewBag.Sl_RecordDate != "")
                sql += " and Sl_RecordDate='" + ViewBag.Sl_RecordDate + "' ";
            if (ViewBag.iput_timeend != "")
                sql += " and Sl_ContractNumber like '%" + ViewBag.Sl_ContractNumber + "%' ";
            var CostPlanmainList = PlmSupervisorlogUIRule.GetAllSupervisorlogForPage(ViewBag.pageNum, ViewBag.numPerPage, "Sl_timestamp", out totalRecord, sql);
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View("SupervisorLogList", new PlmSupervisorLogViewModel { ThePlmSupervisorlogList = CostPlanmainList });
        }
        /// <summary>
        /// 监理员日志添加
        /// </summary>
        /// <returns></returns>
        public ActionResult SupervisorLogAdd(string target, string id)
        {
            ViewBag.OperationType = target;
            //获取模块ID
            ViewBag.MoudleID = GetEntityByUrl(Models.PageURL.监理员日志);
            //附件目录名
            ViewBag.DirWhere = Models.DirName.监理员日志;
            if (target == "add")
            {
                var vm = new PlmSupervisorLogViewModel();
                vm.ThePlmSupervisorlog = new PersonnelLogEntity.Model.PlmSupervisorlogInfo();
                vm.ThePlmSupervisorlog.Sl_UserID = GetLoginUserId;
                vm.ThePlmSupervisorlog.Sl_UserName = GetLoginUserRealName;
                vm.ThePlmSupervisorlog.Sl_RecordDate = DateTime.Now;
                if (GetLoginUserOrganizeEntity.Code == "JL" && GetJLProjectSegmentInfo.Count > 0)
                    vm.ThePlmSupervisorlog.Sl_ContractNumber = GetJLProjectSegmentInfo[0].SEGMENT_CODE;
                else
                {
                    if (GetZDJLProjectSegmentInfo.Count > 0)
                        vm.ThePlmSupervisorlog.Sl_ContractNumber = GetZDJLProjectSegmentInfo[0].SEGMENT_CODE;
                }

                vm.ThePlmSupervisorlog.Sl_RecordUser = GetLoginUserRealName;
                vm.ThePlmSupervisorlog.Sl_SpecialtyPosition = GetLoginUserInfo.WorkgroupFullName;
                vm.ThePlmSupervisorlog.Sl_SupervisorName = GetLoginUserDepartmentName;
                //附件
                var assisId = GenerateRandom();
                var assisIdRet = 0;
                CreateAssistId(PlmSupervisorlogUIRule, assisId, out assisIdRet);
                ViewBag.AssisId = assisIdRet;

                return View(vm);
            }

            else
            {
                var signle = PlmSupervisorlogUIRule.GetPlmSupervisorlogInfoById(id);
                //附件
                var commonFileList = CommonFileUIRule.GetCommonFilesByConditon(signle.Assist_ID, "SupervisorLog_Rules");//SupervisorLog_Rules  BizType类型
                ViewBag.AssisId = signle.Assist_ID;
                ViewBag.FileIds = string.Join(",", commonFileList.Select(t => t.FILE_FILEID));
                ViewBag.DeleteIds = string.Join(",", commonFileList.Select(t => t.FILE_ID));

                var vm = new PlmSupervisorLogViewModel { ThePlmSupervisorlog = signle };
                return View(vm);
            }
        }

        /// <summary>
        /// 监理员日志修改
        /// </summary>
        /// <returns></returns>
        public ActionResult SupervisorLogEdit(string target, string id)
        {
            ViewBag.OperationType = target;
            //获取模块ID
            ViewBag.MoudleID = GetEntityByUrl(Models.PageURL.监理员日志);
            //附件目录名
            ViewBag.DirWhere = Models.DirName.监理员日志;
            var signle = PlmSupervisorlogUIRule.GetPlmSupervisorlogInfoById(id);
            //附件
            var commonFileList = CommonFileUIRule.GetCommonFilesByConditon(signle.Assist_ID, "SupervisorLog_Rules");//SupervisorLog_Rules  BizType类型
            ViewBag.AssisId = signle.Assist_ID;
            ViewBag.FileIds = string.Join(",", commonFileList.Select(t => t.FILE_FILEID));
            ViewBag.DeleteIds = string.Join(",", commonFileList.Select(t => t.FILE_ID));

            var signlesublist = PlmSupervisorlogSubUIRule.GetPlmSupervisorlogSubInfoByFId(id);
            var signleYBsublist = PlmSupervisorlogYBSubUIRule.GetPlmSupervisorlogYbsubInfoByFId(id);
            var vm = new PlmSupervisorLogViewModel { ThePlmSupervisorlog = signle, ThePlmSupervisorlogSubList = signlesublist, ThePlmSupervisorlogYBSubList = signleYBsublist };
            return View(vm);
        }
        /// <summary>
        /// 监理员日志查看
        /// </summary>
        /// <returns></returns>
        public ActionResult SupervisorLogView(string target, string id)
        {
            //获取模块ID
            ViewBag.MoudleID = GetEntityByUrl(Models.PageURL.监理员日志);
            //附件目录名
            ViewBag.DirWhere = Models.DirName.监理员日志;
            var signle = PlmSupervisorlogUIRule.GetPlmSupervisorlogInfoById(id);
            //附件
            var commonFileList = CommonFileUIRule.GetCommonFilesByConditon(signle.Assist_ID, "SupervisorLog_Rules");//SupervisorLog_Rules  BizType类型
            ViewBag.AssisId = signle.Assist_ID;
            ViewBag.FileIds = string.Join(",", commonFileList.Select(t => t.FILE_FILEID));
            ViewBag.DeleteIds = string.Join(",", commonFileList.Select(t => t.FILE_ID));

            var signlesublist = PlmSupervisorlogSubUIRule.GetPlmSupervisorlogSubInfoByFId(id);
            var signleYBsublist = PlmSupervisorlogYBSubUIRule.GetPlmSupervisorlogYbsubInfoByFId(id);
            var vm = new PlmSupervisorLogViewModel { ThePlmSupervisorlog = signle, ThePlmSupervisorlogSubList = signlesublist, ThePlmSupervisorlogYBSubList = signleYBsublist };
            return View(vm);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns>
        public ActionResult SupervisorLogAddHandle(PlmSupervisorLogViewModel vm)
        {
            if (vm == null)
            {
                return new JsonResult()
                {
                    Data = new
                    {
                        statusCode = "300",
                        message = "操作失败",
                    }
                };
            }
            dynamic jsonReturn = new ExpandoObject();
            string operation_str = string.Empty;
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                if (vm.OperationType == "add")
                {
                    operation_str = "添加";
                    vm.ThePlmSupervisorlog.Sl_ID = Guid.NewGuid().ToString();
                    var AssistID = Convert.ToInt32(Request.Form["AssistID"]);
                    vm.ThePlmSupervisorlog.Assist_ID = AssistID;
                    PlmSupervisorlogUIRule.InsertEntity(vm.ThePlmSupervisorlog);
                    //add子表信息
                    foreach (var item in vm.ThePlmSupervisorlogSubList)
                    {
                        if (item != null)
                        {
                            item.SlS_ID = Guid.NewGuid().ToString();
                            item.Sl_ID = vm.ThePlmSupervisorlog.Sl_ID;
                            var cp = PlmSupervisorlogSubUIRule.InsertEntity(item);
                        }

                    }
                    //add子表隐蔽信息
                    foreach (var item in vm.ThePlmSupervisorlogYBSubList)
                    {
                        if (item != null)
                        {
                            item.SlYS_ID = Guid.NewGuid().ToString();
                            item.Sl_ID = vm.ThePlmSupervisorlog.Sl_ID;
                            var cp = PlmSupervisorlogYBSubUIRule.InsertEntity(item);
                        }

                    }
                }
                if (vm.OperationType == "edit")
                {
                    operation_str = "更新";
                    var AssistID = Convert.ToInt32(Request.Form["AssistID"]);
                    vm.ThePlmSupervisorlog.Assist_ID = AssistID;
                    PlmSupervisorlogUIRule.UpdateEntity(vm.ThePlmSupervisorlog);
                    //删除子表信息，再添加
                    PlmSupervisorlogSubUIRule.DeleteEntity(vm.ThePlmSupervisorlog.Sl_ID);
                    foreach (var item in vm.ThePlmSupervisorlogSubList)
                    {
                        if (item != null)
                        {
                            item.SlS_ID = Guid.NewGuid().ToString();
                            item.Sl_ID = vm.ThePlmSupervisorlog.Sl_ID;
                            var cp = PlmSupervisorlogSubUIRule.InsertEntity(item);
                        }

                    }
                    //删除子表隐藏信息，再添加
                    PlmSupervisorlogYBSubUIRule.DeleteEntity(vm.ThePlmSupervisorlog.Sl_ID);
                    foreach (var item in vm.ThePlmSupervisorlogYBSubList)
                    {
                        if (item != null)
                        {
                            item.SlYS_ID = Guid.NewGuid().ToString();
                            item.Sl_ID = vm.ThePlmSupervisorlog.Sl_ID;
                            var cp = PlmSupervisorlogYBSubUIRule.InsertEntity(item);
                        }

                    }
                }
            });
            if (isScuess)
            {
                jsonReturn = new { statusCode = "200", message = string.Format("{0}成功", operation_str), navTabId = "PersonnelLog.PlmSupervisorLog.SupervisorLogList", rel = "", callbackType = "closeCurrent", forwardUrl = "", confirmMsg = "" };
            }
            else
            {
                jsonReturn = new { statusCode = "300", message = string.Format("{0}失败", operation_str) };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }

        /// <summary>
        /// 监理员日志导出
        /// </summary>
        /// <returns></returns>
        public ActionResult SupervisorLogExport(string id)
        {
            var signle = PlmSupervisorlogUIRule.GetPlmSupervisorlogInfoById(id);
            var signlesub = PlmSupervisorlogSubUIRule.GetPlmSupervisorlogSubInfoByFId(id);
            var signleYBsublist = PlmSupervisorlogYBSubUIRule.GetPlmSupervisorlogYbsubInfoByFId(id);
            string fileName = "监理员日志.docx";
            var ret = ExportToWord(fileName, signle, signlesub, signleYBsublist);
            return ret;

        }
        public FileStreamResult ExportToWord(string fileName, PlmSupervisorlogInfo t, List<PlmSupervisorlogSubInfo> signlesub, List<PlmSupervisorlogYbsubInfo> signleYBsublist)
        {
            string path = Server.MapPath("~/Areas/PersonnelLog/Upload/" + fileName);
            string savePath = Server.MapPath("~/Areas/PersonnelLog/Upload/Temp/" + Guid.NewGuid().ToString() + fileName);
            using (DocX docx = DocX.Load(path))
            {
                var rex = new Regex("[0-9]+?");
                docx.Bookmarks.ForEach(f =>
                {
                    var bookMarkName = f.Name;
                    if (rex.IsMatch(bookMarkName))
                    {
                        bookMarkName = f.Name.Substring(0, f.Name.Length - 1);
                    }

                    if (t.ContainProperty(bookMarkName))
                    {
                        var obj = Reflection.GetProperty(t, bookMarkName);
                        var value = obj ?? "";
                        var propertyType = value.GetType().FullName;
                        if (propertyType == "System.DateTime")
                            f.SetText(Convert.ToDateTime(value).ToString("yyyy年MM月dd日"));
                        else
                            f.SetText(value.ToString());
                    }
                });

                //旁站记录表
                foreach (PlmSupervisorlogSubInfo info in signlesub)
                {
                    docx.InsertDocument(base.GetSonExportInfo("监理员日志(旁站记录).docx", info), true);
                }
                //隐蔽工程表
                foreach (PlmSupervisorlogYbsubInfo info in signleYBsublist)
                {
                    docx.InsertDocument(base.GetSonExportInfo("监理员日志(隐蔽工程记录).docx", info), true);
                }
                docx.SaveAs(savePath);
            }
            fileName = HttpUtility.UrlEncode(fileName, Encoding.GetEncoding("UTF-8"));
            FileStream file = new FileStream(savePath, FileMode.Open);
            return File(file, "application/vnd.ms-word", fileName);
        }


        public ActionResult SupervisorLogDelete(string id)
        {
            dynamic jsonReturn = new ExpandoObject();
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                PlmSupervisorlogUIRule.DeleteEntity(id);
                //删除子表信息
                PlmSupervisorlogSubUIRule.DeleteEntity(id);
                //删除子表隐蔽信息
                PlmSupervisorlogYBSubUIRule.DeleteEntity(id);
            });
            if (isScuess)
            {
                jsonReturn = new { statusCode = "200", message = "删除成功", navTabId = "PersonnelLog.PlmSupervisorLog.SupervisorLogList", rel = "", callbackType = "", forwardUrl = "", confirmMsg = "" };
            }
            else
            {
                jsonReturn = new { statusCode = "300", message = "删除失败" };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
    }
}
